package gl.java.umsp;

import gl.java.umsp.event.Event;
import gl.java.umsp.event.EventPublisher;
import gl.java.umsp.router.ChannelRouter;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class UmspConnectionHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("channelActive:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("channelInactive:" + ctx.channel().remoteAddress());
        ctx.close();
        handlerDisconnect(ctx);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        log.warn("exceptionCaught:" + ctx.channel().remoteAddress() + " cause: " + cause);
        ctx.close();
    }

    public static void handlerDisconnect(ChannelHandlerContext ctx) {
        int userID = ChannelRouter.getInstance().unRegisterRouter(ctx.channel());
        ctx.fireUserEventTriggered(Event.buildEvent(Event.USER_EXIT_ROOM,userID));
    }
}
